import geom.PolarVector;
import geom.Vector;

import java.util.ArrayList;
import java.util.Iterator;

import processing.candy.SVG;
import processing.core.PApplet;



public class SimpleBranch {
	ArrayList<Vector> segments;
	ArrayList<SimpleBranch> branches;
	SVG svg;
	public SimpleBranch(Vector s, Vector e){
		segments = new ArrayList<Vector>();
		segments.add(s);
		segments.add(e);
		branches = new ArrayList<SimpleBranch>();
		this.svg = svg;
	}
	
	public void grow(){
		Vector last = segments.get(segments.size()-1);
		Vector l = last.sub(segments.get(segments.size()-2));
		if(l.absLength() < 3) return;
		PolarVector pl = l.getPolar();
		float aincr = (float)(Math.random()*0.2f*Math.PI - 0.1f*Math.PI);
		pl.a = pl.a +  aincr;
		pl.d *= (float)Math.random()*0.15f + 0.85f;
		PApplet.println("D "+ pl.d + "aincr " + aincr + " a "  + pl.a);
		segments.add(last.add(pl.getCartesian()));
		Iterator<SimpleBranch> bit = branches.iterator();
		while(bit.hasNext()){
			bit.next().grow();
		}
		branch();
	}
	
	public void branch(){
		float i = (float)Math.random();
		if(i < 0.80f) return;
		Vector last = segments.get(segments.size()-1);
		Vector l = last.sub(segments.get(segments.size()-2));
		PolarVector pl = l.getPolar();
		float aincr = (float)(Math.random()*0.8f*Math.PI - 0.4f*Math.PI);
		pl.a = pl.a +  aincr;
		pl.d *= (float)Math.random()*0.15f + 0.85f;
		SimpleBranch b = new SimpleBranch(last, last.add(pl.getCartesian()));
		branches.add(b);
	}
	
	public void draw(PApplet pa){
		Iterator<Vector> it = segments.iterator();
		pa.beginShape();
		while(it.hasNext()){
			Vector p = it.next();
			pa.vertex(p.x, p.y);
		}
		pa.endShape();
		
		Iterator<SimpleBranch> bit = branches.iterator();
		while(bit.hasNext()){
			bit.next().draw(pa);
		}
	}
	
}
